package com.lans.linear;

/**
 * @author: lans
 * @date: 2025/2/21
 * @name: 刘宇
 */
public class BoyClircleLinkedList {
    private Boy first = new Boy();

    /**
     * 添加形成环形链表
     * @param nums
     */
    public void addNode(int nums){
        Boy temp = null;
        for(int i=1;i<=nums;i++){
            Boy boy = new Boy(i);
            if(i==1){
                first = boy;
                first.next = first;//自己成环
                temp = first;
            }else{
                temp.next = boy;
                boy.next = first;//新的最后一个节点指向第一个
                temp = boy;//每次记录最后一个节点
            }
        }
    }


    public void showBoy(){
        if(first==null){
            System.out.println("空链表");
            return;
        }
        Boy temp = first;
        while(true){
            System.out.printf("小孩的编号是%d",temp.no);
            //进行判断 不能无限循环的查下去
            if(temp.next == first){
                break;
            }
            temp=temp.next;
        }
    }

    /**
     *  执行淘汰节点
     * @param starNo 从第几个孩子开始
     * @param countNum 表示数了几下
     * @param nums 总的孩子数量
     */
    public void countBoy(int starNo,int countNum,int nums){
        if(first==null||starNo<1||starNo>nums){
            System.out.println("参数有误");
            return;
        }
        Boy helper = first;
        while(true){
            //执行完一圈了
            if(helper.next == first){
                break;
            }
            helper=helper.next;
        }
        //设置从哪里开始数,把first和helper移动到该位置上去
        for(int j=0;j<starNo-1;j++){
            first = first.next;
            helper = helper.next;
        }
        //开始出圈
        while(true){
            if(helper==first){
                break;
            }
            for(int i=0;i<countNum-1;i++){
                first = first.next;
                helper=helper.next;
            }
            System.out.println("");
            System.out.println("编号为"+first.no+"的出圈了");
            first = first.next;
            helper.next = first;
        }
        System.out.printf("编号为%d小孩未出圈",first.no);
    }

    public static void main(String[] args) {
        BoyClircleLinkedList boyLinkedList = new BoyClircleLinkedList();
        boyLinkedList.addNode(5);
        boyLinkedList.showBoy();
        boyLinkedList.countBoy(1,2,5);//从第一个开始，每两个
        //小孩出去一次，一共有五个小孩
    }
}